package controller

import (
	"github.com/gin-gonic/gin"
	"ylm.sl/common/convention/results"
	"ylm.sl/global"
	"ylm.sl/internal/api/request"
	user2 "ylm.sl/internal/api/response"
	"ylm.sl/internal/service"
)

type UserController struct {
	service service.IUserService
}

func NewUserController(service service.IUserService) *UserController {
	return &UserController{service: service}
}

func (uc *UserController) Register(ctx *gin.Context) {
	var dto request.UserRegisterReqDTO
	var err error
	err = ctx.ShouldBind(&dto)
	if err != nil {
		global.Log.ErrContext(ctx, "Register 参数解析 Error: %v", err)
		results.Failure(ctx)
		return
	}
	err = uc.service.Register(ctx, dto)
	if err != nil {
		global.Log.ErrContext(ctx, "Register Error: %v", err)
		results.Failure(ctx)
		return
	}
	results.Success(ctx)
	return
}

func (uc *UserController) Login(ctx *gin.Context) {
	var req request.UserLoginReqDTO
	var err error
	err = ctx.ShouldBind(&req)
	if err != nil {
		global.Log.ErrContext(ctx, "Login 参数解析 Error: %v", err)
		results.Failure(ctx)
		return
	}
	var resp *user2.UserLoginRespDTO
	resp, err = uc.service.Login(ctx, req)
	if err != nil {
		global.Log.ErrContext(ctx, "Login Error: %v", err)
		results.Failure(ctx)
		return
	}

	results.SuccessWithData(ctx, *resp)
	return
}

func (uc *UserController) GetActualUserByUsername(ctx *gin.Context) {
	username := ctx.Param("username")
	result, _ := uc.service.GetUserByUsername(ctx, username)
	results.SuccessWithData(ctx, result)

}

func (uc *UserController) HasUsername(ctx *gin.Context) {
	username := ctx.Query("username")
	result, _ := uc.service.HasUsername(ctx, username)
	results.SuccessWithData(ctx, result)
}

func (uc *UserController) Update(ctx *gin.Context) {
	var requestParam request.UserUpdateReqDTO
	var err error
	err = ctx.ShouldBind(&requestParam)
	if err != nil {

	}
	err = uc.service.Update(ctx, requestParam)
	if err != nil {
		results.Failure(ctx)
		return
	}
	results.Success(ctx)
}

func (uc *UserController) CheckLogin(context *gin.Context) {
	username := context.Query("username")
	token := context.Query("token")

	re, err := uc.service.CheckLogin(context, username, token)
	if err != nil {
		results.Failure(context)
		return
	}
	results.SuccessWithData(context, re)

}

func (uc *UserController) Logout(context *gin.Context) {
	username := context.Query("username")
	token := context.Query("token")

	if err := uc.service.Logout(context, username, token); err != nil {
		global.Log.ErrContext(context, err.Error())
		results.Failure(context)
		return
	}
	results.Success(context)

}
